package com.kfm.jdbc.day02;

import java.sql.*;

public class Demo {


    public static void main(String[] args) {
        /**
         * 事务：
         *  1. MySQL 默认自动提交事务
         *      修改方式： Connection::setAutoCommit(boolean)  true表示自动提交(默认) false手动提交
         *  2. 在不同 Connection 中执行的 SQL 不在同一个事务中
         *  3. 提交事务 Connection::commit()  回滚事务 Connection::rollback()
         */
        Connection connection = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 创建连接
            String url = "jdbc:mysql://localhost:3306/company_info?user=root&password=root";
            connection = DriverManager.getConnection(url);

            // 手动提交事务
            connection.setAutoCommit(false);

            String sql = "update customer set balance = balance - ? where customerName = ?";

            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 设置值
            Object[] params = {100, "老兵"};
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }

            int row = preparedStatement.executeUpdate();

            PreparedStatement preparedStatement1 = connection.prepareStatement(sql);

            preparedStatement1.setObject(1, -100);
            preparedStatement1.setObject(2, "新兵");

            int row1 = preparedStatement1.executeUpdate();
//            int a = 1 / 0;
            // 提交事务
//            connection.rollback();
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }

    }
}
